﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Collections.ObjectModel;

namespace FlexiCommerce.Web.UI.DynamicData
{
    public class ParameterReferenceVisitor : ExpressionVisitor
    {
        private class ParameterCollection : KeyedCollection<string, ParameterExpression>
        {
            protected override string GetKeyForItem(ParameterExpression item)
            {
                return item.Name;
            }
        }

        private ParameterCollection _parameters = new ParameterCollection();

        public ParameterReferenceVisitor() { }

        public ParameterReferenceVisitor(IEnumerable<ParameterExpression> parameters)
        {
            foreach (var p in parameters)
                _parameters.Add(p);
        }

        public ReadOnlyCollection<ParameterExpression> Parameters
        {
            get { return _parameters.ToList().AsReadOnly(); }
        }

        public Expression ReplaceParameters(Expression exp)
        {
            return Visit(exp);
        }

        protected override System.Linq.Expressions.Expression VisitParameter(System.Linq.Expressions.ParameterExpression p)
        {
            if (_parameters.Contains(p.Name))
                p = _parameters[p.Name];
            else
                _parameters.Add(p);

            return base.VisitParameter(p);
        }
    }
}
